﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition.Hosting;
using System.Linq;
using System.Text;
using System.ComponentModel.Composition;

namespace Kugar.Core.Security
{
    public class RMS_PermissionManager
    {
        private IPermissionProvider _provider;
        private CompositionContainer _container;

        [Import(typeof(ICurrentUserProvider))]
        private ICurrentUserProvider _currentUserProvider;

        private static Lazy<RMS_PermissionManager> _defaultManager = new Lazy<RMS_PermissionManager>(defaultManagerCreator,true);

        /// <summary>
        ///     构造函数
        /// </summary>
        /// <param name="currentUserGetter">获取当前用户的函数,允许为空,但如果使用CurrentUserChecker属性时,需先确保该参数不允许为空</param>
        /// <param name="provider">权限处理的提供器,不允许为空</param>
        public RMS_PermissionManager(IPermissionProvider provider)
        {
            //An aggregate catalog that combines multiple catalogs
            var catalog = new AggregateCatalog();
            //Adds all the parts found in the same assembly as the Program class
            catalog.Catalogs.Add(new AssemblyCatalog(typeof(RMS_PermissionManager).Assembly));
            catalog.Catalogs.Add(new DirectoryCatalog(AppDomain.CurrentDomain.BaseDirectory));


            //Create the CompositionContainer with the parts in the catalog
            _container = new CompositionContainer(catalog);

            //Fill the imports of this object
            try
            {
                _container.ComposeParts(this);
            }
            catch (CompositionException compositionException)
            {
                Console.WriteLine(compositionException.ToString());
            }

            _provider = provider;
        }

        ///// <summary>
        /////     获取当前用户的函数,由调用的实际环境进行赋值,允许为空,但如果使用CurrentUserChecker属性时,需先确保该参数不允许为空
        ///// </summary>
        //public Func<int> CurrentUserGetter
        //{
        //    get { return _currentUserProvider; }
        //    set { _currentUserProvider = value; }
        //}

        public IPermissionProvider Provider { get { return _provider; } }

        public IUserGroupManager GroupManager { get { return _provider.GroupManager; } }

        public IUserSpecialManager UserSpecialManager { get { return _provider.UserSpecialPermissionManager; } }

        public IPermissionCheckProvider PermissionChecker { get { return _provider.PermissionManager; } }

        /// <summary>
        ///     返回当前用户的权限检查器
        /// </summary>
        public IUserPermissionChecker CurrentUserChecker
        {
            get
            {
                int currentUserID = -1;

                try
                {
                    currentUserID = _currentUserProvider.GetCurrentUserID();
                }
                catch (Exception)
                {
                    throw;
                }

                if (currentUserID<=0)
                {
                    throw new ArgumentNullException(@"无法读取当前用户ID,请确定当前用户是否已登录");
                }

                return _provider.GetUserPermissionProvider(currentUserID);
            }
        }

        public bool CheckUser(string userName, string password)
        {
            return _provider.CheckUser(userName, password);
        }

        /// <summary>
        ///     返回默认的权限管理器
        /// </summary>
        public static RMS_PermissionManager Default { get { return _defaultManager.Value; } }

        

        private static RMS_PermissionManager defaultManagerCreator()
        {
            var className = Configuration.CustomConfigManager.Default.AppSettings.GetValueByName<string>("RMSProviderType", "Kugar.Core.Security.Providers.MSSQL.MSSQL_PermissionCheckProvider");

            if (string.IsNullOrWhiteSpace(className))
            {
                return null;
            }

            var provider = (IPermissionProvider) Activator.CreateInstance("", className).Unwrap();

            if (provider==null)
            {
                throw new ArgumentNullException("指定类名的提供器不存在或无法实例化");
            }

            return new RMS_PermissionManager(provider);

        }
    }
}
